package com.quanyan.signup.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.signup.constants.Const;
import com.quanyan.signup.entity.db.*;
import com.quanyan.signup.entity.vo.req.ReqExpertMsg;
import com.quanyan.signup.entity.vo.req.ReqSerchReferUser;
import com.quanyan.signup.entity.vo.req.ReqSignUpUser;
import com.quanyan.signup.entity.vo.resp.RespExpertMsg;
import com.quanyan.signup.entity.vo.resp.RespSerchUser;
import com.quanyan.signup.mapper.MyDefineMapper;
import com.quanyan.signup.mapper.TbExpertUserMapper;
import com.quanyan.signup.mapper.TbReferUserMapper;
import com.quanyan.signup.service.SignUpService;
import com.quanyan.sms.service.SmsService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/7/6.
 */
@Service("signUpServiceImpl")
public class SignUpServiceImpl implements SignUpService{

    @Autowired
    private MyDefineMapper myDefineMapper;

    @Autowired
    private TbExpertUserMapper tbExpertUserMapper;

    @Autowired
    private TbReferUserMapper tbReferUserMapper;

   /* @Autowired
    private MyRedisTemplate redisTemplate;//缓存*/


  /*  *//**
     * 获取城市区域信息
     * @return
     *//*
    @Override
    public APIResponse<List<RespCityDistrict>> getCityDistrict() {
        //读缓存
        RedisKey rk = new RedisKey(RedisConstants.VOTE_FORWORD_CACHE_PREFIX, Const.CITY_KEY);
        List<RespCityDistrict> respCityDistricts= (List<RespCityDistrict>) redisTemplate.get(rk);
        if (respCityDistricts==null){
            respCityDistricts=myDefineMapper.getAllCity();
            for (int i=0;i<respCityDistricts.size();i++){
                RespCityDistrict respCityDistrict=respCityDistricts.get(i);
                List<TbDistrict> tbDistrictList=myDefineMapper.getAllDistrict(respCityDistrict.getId());
                respCityDistrict.setTbDistrictList(tbDistrictList);
            }
            redisTemplate.set(rk,respCityDistricts);
        }
        return APIResponse.returnSuccess( respCityDistricts);
    }*/

    /**
     * 用户报名
     * @param reqSignUpUser
     * @return
     */

    @Override
    @Transactional
    public APIResponse signUpUser(ReqSignUpUser reqSignUpUser) {

        TbExpertUser tbExpertUser=new TbExpertUser();
        try {
            BeanUtils.copyProperties(tbExpertUser,reqSignUpUser);
        } catch (Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail("报名失败");
        }
        //该用户是否已报名
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        tbExpertUserExample.createCriteria().andMobileEqualTo(reqSignUpUser.getMobile());
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
        if(tbExpertUserList.size()>0){//该用户已经报名过
            TbExpertUser tbExpertUser1=tbExpertUserList.get(0);//报名达人信息
            String name=tbExpertUser1.getName();
            if (!StringUtil.isBlankOrNull(name)){
                return APIResponse.returnFail("您已报名");
            }
            String referMobile=tbExpertUser1.getRefermobile();
            if (StringUtil.isBlankOrNull(referMobile)){//推荐人为空，跟新推荐人手机号　　自己推荐自己，做处理
                tbExpertUser.setRefermobile(null);
            }else {
                tbExpertUser.setRefermobile(tbExpertUser1.getRefermobile());
            }
            tbExpertUserMapper.updateByExampleSelective(tbExpertUser,tbExpertUserExample);
            return APIResponse.returnSuccess("跟新信息成功");
        }

        //查看报名人的推荐人信息
        String mobileRefer=reqSignUpUser.getRefermobile();
        if (!StringUtil.isBlankOrNull(mobileRefer)){//通过用户推荐进入报名页面
            TbReferUserExample tbReferUserExample=new TbReferUserExample();
            tbReferUserExample.createCriteria().andMobileEqualTo(mobileRefer);
            List<TbReferUser> tbReferUserList=tbReferUserMapper.selectByExample(tbReferUserExample);
            if (tbReferUserList.size()>0){//推荐人用户存在
                TbReferUser tbReferUser=tbReferUserList.get(0);
                if(tbReferUser.getMobile().equals(tbExpertUser.getMobile())){//通过链接生成二维码，自己扫描报名
                    tbExpertUser.setRefermobile(null);
                }else{
                    tbReferUser.setAllNum(tbReferUser.getAllNum()+1);
                }
                tbReferUserMapper.updateByExampleSelective(tbReferUser,tbReferUserExample);
            } else{
                //推荐人是否报名
                TbExpertUserExample tbExpertUserExampleT=new TbExpertUserExample();
                tbExpertUserExampleT.createCriteria().andMobileEqualTo(mobileRefer);
                List<TbExpertUser> tbExpertUserListT=tbExpertUserMapper.selectByExample(tbExpertUserExampleT);
                TbReferUser tbReferUser=new TbReferUser();
                tbReferUser.setAllNum(1);
                tbReferUser.setMobile(mobileRefer);
                if(tbExpertUserListT.size()>0){//推荐人也是报名人
                    TbExpertUser tbExpertUsers=tbExpertUserListT.get(0);
                    tbReferUser.setSignTime(tbExpertUsers.getSignTime());//获取注册时间
                }else{
                    tbReferUser.setSignTime(new Date());
                }
                if (tbExpertUser.getRefermobile().equals(tbExpertUser.getMobile())){//用户通过自己的链接进入报名页报名，推荐人不存在
                    tbExpertUser.setRefermobile(null);
                    tbReferUser.setAllNum(0);
                }
                tbReferUserMapper.insertSelective(tbReferUser);
            }
        }
        //保存报名人信息
        tbExpertUserMapper.insertSelective(tbExpertUser);
        return APIResponse.returnSuccess("报名成功");
    }

    @Autowired
    private SmsService smsService;

    /**
     * 用户报名第二步
     * @param paramMap
     * @return
     */
    @Override
    public APIResponse signUpUserToNext(Map<String,Object> paramMap) {
        if (paramMap!=null){
            TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
            tbExpertUserExample.createCriteria().andMobileEqualTo((String)paramMap.get("mobile"));
            List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
            if(tbExpertUserList.size()>0){//说明用户存在，防止直接通过url进入该页面
                TbExpertUser tbExpertUser= tbExpertUserList.get(0);
                tbExpertUser.setName((String) paramMap.get("name"));
                tbExpertUser.setPhotoUrl((String) paramMap.get("photoUrl"));
                int oex= (Integer) paramMap.get("expChoice");
                tbExpertUser.setExpChoice((byte)oex);
                tbExpertUserMapper.updateByExampleSelective(tbExpertUser,tbExpertUserExample);
                return APIResponse.returnSuccess("完善报名信息成功");
            }
        }

        return APIResponse.returnFail("完善报名信息失败，请重试");
    }

    /**
     * 推荐人数查看
     * @param mobile
     * @return
     */
    @Override
    public APIResponse<Integer> referUserNumber(String mobile) {
        TbReferUserExample tbReferUserExample=new TbReferUserExample();
        tbReferUserExample.createCriteria().andMobileEqualTo(mobile);
        List<TbReferUser> tbReferUserList=tbReferUserMapper.selectByExample(tbReferUserExample);
        if(tbReferUserList.size()>0){
            TbReferUser tbReferUser=tbReferUserList.get(0);
            if (tbReferUser.getAllNum()>0){
                return APIResponse.returnSuccess(tbReferUser.getAllNum());
            }
        }
        return APIResponse.returnFail(50,"推荐用户不存在，请重试");
    }

    /**
     * 查询推荐人信息
     * @param reqSerchReferUser
     * @return
     */
    @Override
    public APIResponse<List<RespSerchUser>> searchReferUser(ReqSerchReferUser reqSerchReferUser) {
        Map<String,Object> paramMap=reqSerchReferUser.getParamMap();
        if(paramMap==null){
            return APIResponse.returnFail(60,"手机号不能为空");
        }
        //查询总数量
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        tbExpertUserExample.createCriteria().andRefermobileEqualTo((String) paramMap.get("referMobile"));
        int totalCount=tbExpertUserMapper.countByExample(tbExpertUserExample);
        //分页
        TbExpertUserExample tbExpertUserExampleT=new TbExpertUserExample();
        Page page=new Page(reqSerchReferUser.getPageNum(),reqSerchReferUser.getPageSize(),totalCount);
        tbExpertUserExampleT.createCriteria().andRefermobileEqualTo((String) paramMap.get("referMobile"));
        tbExpertUserExampleT.setPage(page);
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExampleT);
        if (tbExpertUserList.size()==0){
            return APIResponse.returnFail("没有更多数据了");
        }
        List<RespSerchUser> respSerchUserList=new ArrayList<RespSerchUser>();
        for (int i=0;i<tbExpertUserList.size();i++){
            RespSerchUser respSerchUser=new RespSerchUser();
            try {
                BeanUtils.copyProperties(respSerchUser,tbExpertUserList.get(i));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            respSerchUserList.add(respSerchUser);
        }
        return APIResponse.returnSuccess(respSerchUserList);
    }

    /**
     * 微信达人发送手机号查看状态
     * @param mobile
     * @return
     */
    @Override
    public APIResponse<String> queryUserStatuByPhone(String mobile) {
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        tbExpertUserExample.createCriteria().andMobileEqualTo(mobile);
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
        if (tbExpertUserList.size()>0){
            TbExpertUser tbExpertUser=tbExpertUserList.get(0);
            String content=null;
            Byte statu=tbExpertUser.getSignStatu();
            if (Const.GET_SIGN==statu){
                content="感谢您参与百灵鸟达人招募活动，我们将在48小时内审核报名信息。";
            }else if (Const.GET_LINE==statu){
                content="恭喜您！您已成功通过百灵鸟达人招募活动线上筛选。我们会在48小时内与您取得联系，并以短信方式告知您具体的面试详情，请保持手机畅通！";
            }else if (Const.OUT_LIEN==statu){
                content="非常抱歉您未能通过百灵鸟达人招募活动线上筛选，您还可以推荐您好友参与我们的活动，一旦成功签约，您将获得200-500元的推荐现金大奖。";
            }else if (Const.GET_INTERVIE==statu){
                String exp=tbExpertUser.getExpert()==Const.PRETTY?"魅力型":"实力派";
                content="恭喜您！您已通过百灵鸟达人招募活动的面试成为"+exp+"达人。我们会在24小时内与您取得联系，并以短信方式告知您具体的培训及签约详情，请保持手机畅通！";
            }else if (Const.OUT_INTERVIE==statu){
                content="非常抱歉您未能通过百灵鸟达人招募活动面试，您还可以推荐您的好友参与我们的活动，一旦成功签约，您将获得200-500元的推荐现金大奖。";
            }else if (Const.SIGN_EXPERT==statu){
                content="恭喜您加入百灵鸟，让我们一起开始运动吧！";
            }
            return APIResponse.returnSuccess(content);
        }
        return APIResponse.returnFail("您还未报名");
    }

    /**
     * 根据手机号查询达人信息，修改
     * @param mobile
     * @return
     */
    @Override
    public APIResponse<RespExpertMsg> queryExpertMsgByMobile(String mobile) {
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        tbExpertUserExample.createCriteria().andMobileEqualTo(mobile);
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
        if(tbExpertUserList.size()>0){
            RespExpertMsg respExpertMsg=new RespExpertMsg();
            try {
                BeanUtils.copyProperties(respExpertMsg,tbExpertUserList.get(0));
                return APIResponse.returnSuccess(respExpertMsg);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return APIResponse.returnFail("该达人不存在");
    }

    /**
     * 根据手机号，跟新部分达人信息
     * @param reqExpertMsg
     * @return
     */
    @Override
    public APIResponse updateExpertMsgByMobile(ReqExpertMsg reqExpertMsg) {
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        tbExpertUserExample.createCriteria().andMobileEqualTo(reqExpertMsg.getMobile());
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
        if (tbExpertUserList.size()>0){
            TbExpertUser tbExpertUser=tbExpertUserList.get(0);
            tbExpertUser.setName(reqExpertMsg.getName());
            tbExpertUser.setGender(reqExpertMsg.getGender());
            tbExpertUser.setPhotoUrl(reqExpertMsg.getPhotoUrl());
            int tpFlag=tbExpertUserMapper.updateByExampleSelective(tbExpertUser,tbExpertUserExample);
            return tpFlag>0?APIResponse.returnSuccess():APIResponse.returnFail("跟新失败");
        }
        return APIResponse.returnFail("非法跟新操作");
    }

    /**
     * 检查手机号是否是达人
     * @param mobile
     * @return
     */
    @Override
    public APIResponse checkExpertMobile(String mobile) {
        TbExpertUserExample tbExpertUserExample=new TbExpertUserExample();
        tbExpertUserExample.createCriteria().andMobileEqualTo(mobile);
        List<TbExpertUser> tbExpertUserList=tbExpertUserMapper.selectByExample(tbExpertUserExample);
        return tbExpertUserList.size()>0?APIResponse.returnSuccess():APIResponse.returnFail("失败");
    }
}
